import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);


// 动态导入所有模块
const modulesFiles = require.context('@/store/modules', true, /\.js$/);
const DynamicModules = {};

modulesFiles.keys().forEach((fileName) => {
	const moduleName = fileName.replace(/(\.\/|\.js)/g, '');
	DynamicModules[moduleName] = modulesFiles(fileName).default;
});


const store = new Vuex.Store({
	state: {
		isConnected: false,//socket链接状态
		reconnectCount:0,//重连次数
	},
	mutations: {
		$uStore(state, payload) {
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if (nameArr.length >= 2) {
				let obj = state[nameArr[0]];
				for (let i = 1; i < len - 1; i++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value;
			}
			console.log(state[payload.name]);
		}
	},
	modules: {
		...DynamicModules
	},
})

export default store;
